import requests
import json
from app import create_app,db
from app.models import Ifgapi
import time

app = create_app('default')

class ifagou():
    def __init__(self):
        self.userid = None
        self.secret = None
        self.headers = {
            "Content-Type":"application/x-www-form-urlencoded"
        }

    def setkey(self,userid,secret=None):
        self.userid = userid
        if secret:
            self.secret = secret
        else:
            with app.app_context():
                res = Ifgapi.query.filter_by(userid=userid).first()
                if res:
                    self.secret = res.secret

    def setstatus(self):
        today = int(time.strftime("%Y%m%d", time.localtime()))
        with app.app_context():
            db.session.query(Ifgapi).filter_by(userid=self.userid).update({'statusdate': today})
            db.session.commit()
            db.session.close()


    def tosubmit(self,title,content):
        apiurl = "https://api.ifagou.com/api/submitRevise.html"
        data = {
            "userId":self.userid,
            "secret":self.secret,
            "type":"2",
            "title":title,
            "content":content,
            "useWords":"0"
        }
        res = requests.post(apiurl,headers = self.headers,data = data)
        if res.status_code == 200:
            con = res.content.decode("utf-8")
            conjs = json.loads(con)
            if conjs['code'] == 1:
                return 1 , conjs['data']
            else:
                self.setstatus()
                return 0 , None
        return -1 , None

    def getdata(self,docIdList):
        apiurl = "https://api.ifagou.com/api/queryReviseResult.html"
        data = {
            "userId":self.userid,
            "secret":self.secret,
            "docIdList":docIdList
        }

        res = requests.post(apiurl, headers=self.headers, data=data)
        if res.status_code == 200:
            con = res.content.decode("utf-8")
            conjs = json.loads(con)
            if conjs['code'] == 1:
                return conjs['data']
        return False





